#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <sys/types.h>        
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include "log.hpp"
using namespace std;

Log log;
enum {
    SOCKET_ERR,
    CONNECT_ERR,
};

void Usage(const char* string)
{
    cout << "\n\rUsage: " << string << " serverIp serverPort\n\n";  
}

int 
main(int argc, char* argv[])
{
    if(argc != 3) {
        Usage(argv[0]);
        return -1;
    }

    // 创建套接字
    int socketFd = socket(AF_INET, SOCK_STREAM, 0);

    if(socketFd == -1) {
        // 创建失败
        log(FATAL, "客户端创建套接字失败, fd: %d, 原因: %s\n", socketFd, strerror(errno));
        close(socketFd);
        exit(SOCKET_ERR);
    }
    log(INFO, "客户端创建套接字成功\n");
    // 获得服务端的IP和端口号
    string serverIp = argv[1];
    uint16_t serverPort = stoi(argv[2]);
    // 构建服务器信息
    sockaddr_in server;
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(serverPort);
    inet_pton(AF_INET, serverIp.c_str(), &(server.sin_addr));
    
    if(connect(socketFd, (sockaddr*)&server, sizeof server) < 0) {
        // 连接失败
        log(FATAL, "客户端连接失败, 原因: %s\n", strerror(errno));
        close(socketFd);
        exit(CONNECT_ERR);
    }
    log(INFO, "客户端连接成功, 服务器ip: %s, 服务器端口号: %d\n", serverIp.c_str(), serverPort);

    string msg;
    // 收发消息
    while (true) {
        printf("Please enter$ ");
        getline(cin, msg);
        write(socketFd, msg.c_str(), msg.size());

        char buf[1024];
        ssize_t n = read(socketFd, buf, sizeof(buf) - 1);
        if(n > 0) {
            buf[n] = 0;
            printf("%s\n", buf); 
        }
    }

    close(socketFd);
}